package com.ssyc.common.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nim.uikit.common.activity.UI;
import com.ssyc.common.R;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.ARouterUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.manager.StateBarManager;
import com.ssyc.common.utils.ExitLoginUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.statelayoutlib.StateLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Stack;


/**
 * Created by Administrator on 2017/12/21 0021.
 */

public abstract class BaseActivity extends UI {

    private static boolean isMiUi = false;


    /**
     * 防止点击过快的时间间隔
     */
    public static final long NO_DOUBLE_CLICK_TIME = 500;


    //状态控制视图
    protected StateLayoutManager statusLayoutManager;

    //根视图
    protected LinearLayout llBaseMain;
    //通用头布局
    protected LinearLayout llBaseHead;
    //标题栏左边的返回
    protected RelativeLayout rlBaseBack;
    //显示标题的TextView
    protected TextView tvBaseTitle;
    //标题栏右边的包含图标的布局
    protected RelativeLayout rlBaseEnjoy;
    //标题栏右边的图标
    protected ImageView lvBaseEnjoy;
    //标题栏右边的文字
    protected TextView tvBaseRight;

    protected Context context;

    //状态栏
//    private StatusBarView statusBarView;


    //被踢下线的标识
    public static int KICKOUT = 0x160;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_base_view);

        //初始化上下文
        context = this;

        //配置状态视图的方法
        initStatusLayout();

        //添加状态视图到根视图上
        initBaseView();

        //使用注解绑定
//      ButterKnife.bind(this);

        //初始化标题栏
        initTitle();

        //设置6.0以后沉浸状体栏的问题
        StateBarManager.setBarWithUltimateBar(this, getResources().getColor(R.color.state_color),
                getResources().getColor(R.color.nav_color));

        //每次初始化的时候就将当前activity加入到全局的ActivityStack中
        AppManager.getInstance().add(this);

        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //初始化数据的方法
        init();

    }


    /**
     * 初始化标题栏的方法
     */
    private void initTitle() {
        llBaseMain = findViewById(R.id.ll_base_main);
        llBaseHead = findViewById(R.id.ll_base_head);
        tvBaseTitle = findViewById(R.id.tv_base_title);
        rlBaseBack = findViewById(R.id.rl_base_back);
        rlBaseEnjoy = findViewById(R.id.rl_base_enjoy);
        tvBaseRight = findViewById(R.id.tv_base_right);
        lvBaseEnjoy = findViewById(R.id.lv_base_enjoy);
        //状态栏布局
//        statusBarView = (StatusBarView) findViewById(R.id.stateview);

        //设置状态栏是否显示的方法
//        if (isNeedShowStateView()) {
//            statusBarView.setVisibility(View.VISIBLE);
//        } else {
//            statusBarView.setVisibility(View.GONE);
//        }

        //设置显示和隐藏的方法
        if (isNeedShowTitle()) {
            llBaseHead.setVisibility(View.VISIBLE);
            tvBaseTitle.setText(setTitleText());
            rlBaseBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        } else {
            llBaseHead.setVisibility(View.GONE);
        }

    }

    /**
     * 设置是否需要显示状态栏的方法
     * 当当前Activity需要需要设置为全屏时，该方法返回false,否则返回true
     */
//    protected abstract boolean isNeedShowStateView();

    /**
     * 设置标题显示的方法,有些页面可能需要自定义头部所以提供该方法
     * true为显示,false为不显示
     */
    protected abstract boolean isNeedShowTitle();

    /**
     * 设置头部标题的方法
     */
    protected abstract String setTitleText();

    /**
     * 将状态视图添加到根视图上
     */
    private void initBaseView() {
        LinearLayout ll_main = findViewById(R.id.ll_base_main);
        ll_main.addView(statusLayoutManager.getRootLayout());
    }

    /**
     * 初始化状态管理栏目视图
     */
    protected void initStatusLayout() {
        statusLayoutManager = StateLayoutManager.newBuilder(this)
                .contentView(getContentLayout())
                .emptyDataView(R.layout.base_activity_emptydata)
                .errorView(R.layout.base_activity_error)
                .loadingView(R.layout.base_activity_loading)
                .netWorkErrorView(R.layout.base_activity_networkerror)
                .build();
    }

    /**
     * 返回内容布局ID的方法
     *
     * @return
     */
    protected abstract int getContentLayout();

    /**
     * 初始化的方法
     */
    protected abstract void init();


    /**
     * 提供给子类设置加载布局背景的方法
     *
     * @param colorId
     */
    protected void setLoadingBg(int colorId) {
        if (statusLayoutManager != null) {
            RelativeLayout rlOutSide = statusLayoutManager.getRootLayout().findViewById(R.id.rl_loading_out);
            rlOutSide.setBackgroundResource(colorId);
        }
    }

    /**
     * 显示Activity内容视图的方法
     * 如果当前Activity页面没有网络请求操作时,在init()方法中直接调用该方法
     */
    protected void showContent() {
        statusLayoutManager.showContent();
    }

    /**
     * 显示空数据视图的方法
     */
    protected void showEmptyData() {
        statusLayoutManager.showEmptyData();
        LinearLayout ll_empty_data = findViewById(R.id.ll_empty_data);
        ll_empty_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                init();
            }
        });
    }


    /**
     * 网络请求错误需要显示的页面
     */
    protected void showError() {
        statusLayoutManager.showError();
        LinearLayout ll_error_data = findViewById(R.id.ll_error_data);
        ll_error_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                init();
            }
        });
    }

    /**
     * 无Wifi或者4G网络时提示用户打开网络设置的方法
     * 该方法一般在基类中通过工具类判断是否有检测到网络,然后处理即可
     */
    protected void showNetWorkError() {
        statusLayoutManager.showNetWorkError();
        LinearLayout ll_set_network = findViewById(R.id.ll_set_network);
        ll_set_network.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
                startActivity(intent);
            }
        });
    }

    /**
     * 显示加载框的方法
     */
    protected void showLoading() {
        statusLayoutManager.showLoading();
    }


    /**
     * EventBus的接受事件的方法
     *
     * @param busInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busEvent(BusInfo busInfo) {
        if (null != busInfo && KICKOUT == busInfo.getType()) {
            showKickOutPop();
        }
    }

    /**
     * 弹出被T下线的PopUpWindow
     */
    private void showKickOutPop() {

        ExitLoginUtil.exitLogin(BaseActivity.this);

        Stack<Activity> activityStack = AppManager.getInstance().getActivityStack();
        //如果列表中的最后一个activity 跟当前activity相同时，则可以弹出对话框
        if (activityStack.get(activityStack.size() - 1).getClass() == this.getClass()) {

            //弹出被踢下线的对话框
            // 创建构建器
//            AlertDialog.Builder builder = new AlertDialog.Builder(this);
//            builder.setCancelable(false);
//            builder.setTitle("提示")
//                    .setMessage("您的账号在其它位置登录,您已经被踢下线~")
//                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {// 消极
//
//                        @Override
//                        public void onClick(DialogInterface dialog,
//                                            int which) {
//                            //关闭栈中所有的Activity
//                            ARouterUtils.start("/main/ChooseRoleActivity");
//                            AppManager.getInstance().removeOthers();
//                        }
//                    });
//            builder.create().show();

            //弹框
            PopUpManager.showPopByMatchParentNoTouch(this, R.layout.base_pop_exit_sys, 0.3f, this, new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {
                    TextView tv_again = view.findViewById(R.id.tv_again);
                    TextView tv_msg = view.findViewById(R.id.tv_msg);
                    tv_msg.setText("您的账号在其它位置登录,您已经被踢下线~");
                    tv_again.setVisibility(View.INVISIBLE);
                    TextView tv_over = view.findViewById(R.id.tv_over);
                    tv_again.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!isDoubleClick(v)) {
                                //取消
                                PopUpManager.dismiss();
                            }

                        }
                    });

                    tv_over.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!isDoubleClick(v)) {
                                ARouterUtils.start("/main/ChooseRoleActivity");
                                AppManager.getInstance().removeOthers();
                                //取消
                                PopUpManager.dismiss();
                            }

                        }
                    });
                }
            });

        }
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    /**
     * 全局事件分发 实现 触摸非输入框控件 隐藏键盘
     *
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 是否隐藏软键盘
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();

//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                // 点击的是输入框区域，保留点击EditText的事件
//                return false;
//            } else {
//                return true;
//            }


            if (event.getX() > 0 && event.getX() < ScreenUtils.getScreenWidth(this)
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    /*--------------------------------------针对小米手机和魅族手机改变状态文字颜色为黑色的方法----------------------------------------------------------*/

    /**
     * 设置小米黑色状态栏字体
     */
    @SuppressLint("PrivateApi")
    private void setMIUIStatusBarDarkMode() {
        if (isMiUi) {
            Class<? extends Window> clazz = getWindow().getClass();
            try {
                int darkModeFlag;
                Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                extraFlagField.invoke(getWindow(), darkModeFlag, darkModeFlag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 静态域，获取系统版本是否基于MIUI
     */

    static {
        try {
            @SuppressLint("PrivateApi") Class<?> sysClass = Class.forName("android.os.SystemProperties");
            Method getStringMethod = sysClass.getDeclaredMethod("get", String.class);
            String version = (String) getStringMethod.invoke(sysClass, "ro.miui.ui.version.name");
            isMiUi = version.compareTo("V6") >= 0 && Build.VERSION.SDK_INT < 24;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置魅族手机状态栏图标颜色风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean setMeiZuDarkMode(Window window, boolean dark) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 24) {
            return false;
        }
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @SuppressLint("InlinedApi")
    private int getStatusBarLightMode() {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (isMiUi) {
                result = 1;
            } else if (setMeiZuDarkMode(getWindow(), true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = 3;
            }
        }
        return result;
    }

    @SuppressLint("InlinedApi")
    protected void setStatusBarDarkMode() {
        int type = getStatusBarLightMode();
        if (type == 1) {
            setMIUIStatusBarDarkMode();
        } else if (type == 2) {
            setMeiZuDarkMode(getWindow(), true);
        } else if (type == 3) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    /**
     * 隐藏加载视图的方法
     *
     * @param loadingView 加载视图
     * @param isShowToast 是否需要弹吐司
     */
    protected void showLoadingView(View loadingView, boolean isShowToast) {
        if (null != loadingView) {
            loadingView.setVisibility(View.GONE);
        }
        if (isShowToast) {
            UiUtils.Toast(BaseApplication.ERROR, false);
        }
    }

    /**
     * 防止按钮重复点击的方法
     */
    protected boolean isDoubleClick(View v) {
        Object tag = v.getTag(v.getId());
        long beforeTimemiles = tag != null ? (long) tag : 0;
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        v.setTag(v.getId(), timeInMillis);
        return timeInMillis - beforeTimemiles < NO_DOUBLE_CLICK_TIME;
    }

}
